# 单例模式，也叫单件模式，是指一个类只能创建一个实例。

# 1、通过__new__方法实现
# class SingleCaseMode(object):
#     # 用来记录单例对象的引用
#     obj = None
#
#     def __new__(cls, *args, **kwargs):
#         if cls.obj is None:
#             cls.obj = object.__new__(cls)
#         return cls.obj
#
#     def __init__(self):
#         pass


# 2、通过装饰器实现
def singleton(cls):
    # 创建一个字典，用来保存类的实例
    instance = {}

    def get_instance(*args, **kwargs):
        if cls not in instance:
            instance[cls] = cls(*args, **kwargs)
        return instance[cls]

    return get_instance


@singleton
class SingleCaseMode(object):
    def __init__(self):
        pass


a1 = SingleCaseMode()
a2 = SingleCaseMode()
a3 = SingleCaseMode()
print(a1, a2)
print(a2 is a3)

